<?php


namespace app\common\model;


use app\common\enum\MainEnum;
use app\common\exception\LogicException;
use app\common\service\rabbitMQ\OrderCreated;
use app\common\service\rabbitMQ\OrderPaymentTimedOut;
use app\common\service\rabbitMQ\RabbitMQBusinessInterface;
use app\common\service\Redis;

class OrderModel extends CommonModel
{
    protected $name = 'order';

    public static function onAfterWrite($model)
    {
        if ($model->getData('status') === MainEnum::ORDER_STATUS_WAIT_PAY) {
            $expireTimestamp = Redis::getStoreConfig('orderPaymentTimedOutMaxTimestamp') * 1000;
            OrderPaymentTimedOut::publisher(
                [
                    'order_nb'         => $model->getData('nb'),
                    'expire_timestamp' => $expireTimestamp,
                ],
                $expireTimestamp
            );
        }
    }

    public static function onAfterInsert($model)
    {
        OrderCreated::publisher(['order_nb' => $model->getData('nb')]);
    }

    public function setWxPrepayInfoAttr($v)
    {
        return json_encode($v);
    }

    public function getWxPrepayInfoAttr($v)
    {
        return json_decode($v, true);
    }

    public function getPriceDiscountDescAttr($v)
    {
        return json_decode($v, true);
    }

    public function setPriceDiscountDescAttr($v)
    {
        return json_encode($v, JSON_UNESCAPED_UNICODE);
    }

    public function setCancelTimeAttr($v)
    {
        return date('Y-m-d H:i:s', $v);
    }

    public function setStatusAttr($v, $data)
    {
        if ($v === MainEnum::ORDER_STATUS_CANCEL || $v === MainEnum::ORDER_STATUS_REFUND) {
            //退还优惠券
            if ($data['coupon_id'] && $data['coupon_status'] === MainEnum::ORDER_COUPON_STATUS['已使用']) {
                $userCouponModel = (new UserCouponModel())->getUserCoupon(
                    [
                        [
                            'user_id',
                            '=',
                            $data['user_id'],
                        ],
                        [
                            'coupon_id',
                            '=',
                            $data['coupon_id'],
                        ],
                    ]
                );
                if ($userCouponModel) {
                    $userCouponModel->status   = MainEnum::COUPON_USER_STATUS['待使用'];
                    $userCouponModel->use_time = null;
                    $userCouponModel->save();
                    $this->set('coupon_status', MainEnum::ORDER_COUPON_STATUS['已退还']);
                    $this->set('coupon_return_time', NOW_TIME);
                }
            }
        }
        return $v;
    }

    public function setFhTimeAttr($v)
    {
        return date('Y-m-d H:i:s', $v);
    }

    public function setSignForTimeAttr($v)
    {
        return date('Y-m-d H:i:s', $v);
    }

    public function setCouponReturnTimeAttr($v)
    {
        return date('Y-m-d H:i:s', $v);
    }

    public function setRefundTimeAttr($v)
    {
        return date('Y-m-d H:i:s', $v);
    }

    public function orderListInfo(): \think\model\relation\HasMany
    {
        return $this->hasMany(OrderListModel::class, 'order_nb', 'nb');
    }

    public function userInfo(): \think\model\relation\HasOne
    {
        return $this->hasOne(UserModel::class, 'id', 'user_id');
    }

    public function packageCompanyInfo(): \think\model\relation\HasOne
    {
        return $this->hasOne(PackageCompanyModel::class, 'id', 'package_company_id');
    }

    public function getExtendStatusTextAttr($v, $data): ?string
    {
        return self::getOrderStatusText($data['status']);
    }

    public static function getOrderStatusText($status): ?string
    {
        switch ($status) {
            case MainEnum::ORDER_STATUS_WAIT_PAY:
                return '待付款';
            case MainEnum::ORDER_STATUS_WAIT_SHIPMENT:
                return '待发货';
            case MainEnum::ORDER_STATUS_WAIT_SIGN_FOR:
                return '待签收';
            case MainEnum::ORDER_STATUS_SIGN_FOR_ED:
                return '已签收';
            case MainEnum::ORDER_STATUS_DONE_BUT_WAIT_APPRAISE:
                return '待评价';
            case MainEnum::ORDER_STATUS_DONE_AND_APPRAISE:
                return '已完成';
            case MainEnum::ORDER_STATUS_CANCEL:
                return '已取消';
            case MainEnum::ORDER_STATUS_REFUND:
                return '已退款';
            default:
                return '';
        }
    }

    public function getOrder($where = [])
    {
        return $this->with(
            [
                'orderListInfo',
                'orderListInfo' => ['refundInfo'],
                'packageCompanyInfo',
            ]
        )->order(
            [
                'create_time' => 'desc',
            ]
        )->where($where)->append(
            [
                'extend_status_text',
                'orderListInfo' => [
                    'extend_status_text',
                    'refundInfo.extend_status_text',
                ],
            ]
        )->find();
    }

    public function getOrderList($where = [])
    {
        return $this->with(
            [
                'orderListInfo',
                'orderListInfo' => ['refundInfo'],
                'packageCompanyInfo',
            ]
        )->order(
            [
                'create_time' => 'desc',
            ]
        )->where($where)->append(
            [
                'extend_status_text',
                'orderListInfo' => [
                    'extend_status_text',
                    'refundInfo.extend_status_text',
                ],
            ]
        )->select();
    }

    public function getOrderListPaginate($where = [], $page = 1, $limit = 10)
    {
//        vd($where, $page, $limit);
        return $this->with(
            [
                'userInfo',
                'packageCompanyInfo',
                'orderListInfo',
                'orderListInfo' => ['refundInfo'],
            ]
        )->order(
            [
                'create_time' => 'desc',
            ]
        )->where($where)->append(
            [
                'extend_status_text',
                'orderListInfo' => [
                    'extend_status_text',
                    'refundInfo.extend_status_text',
                ],
            ]
        )->paginate(
            [
                'page'      => $page,
                'list_rows' => $limit,
            ]
        );
    }
}